package com.wanxi.util;

import com.wanxi.model.UserModel;

import java.sql.*;
import java.util.List;

/**
 * 一般情况下六大步骤
 * 1.加载驱动：只加载一次
 * 2.取得连接
 * 3.编译sql语句
 * 4.执行sql语句
 * 5.得到返回结果
 * 6.关闭连接
 */
public class JDBC {
    private static final String USER = "canyin04";
    private static final String PASS = "123456";
    private static final String URL = "jdbc:mysql://121.199.55.96:3306/canyin04?serverTimezone=UTC&characterEncoding=UTF-8";
//    private static PreparedStatement preparedStatement = null;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static Connection getConn() {

        try {
            return DriverManager.getConnection(URL, USER, PASS);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 增加，修改，删除
     *
     * @param sql
     * @return
     */
    public static int update(String sql) {
        try (PreparedStatement preparedStatement = getConn().prepareStatement(sql)) {
//        编译sql语句
//            preparedStatement = getConn().prepareStatement(sql);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static ResultSet query(String sql) {
        PreparedStatement preparedStatement = null;
        try {
//        编译sql语句
            preparedStatement = getConn().prepareStatement(sql);
//            对返回的结果集进行解析：因为属于不同的表，所以解析应该放入不同的类
//            所以，暂时放入不同的dao层解析
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static void close() {
//        if (preparedStatement != null) {
//            try {
//                preparedStatement.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//    }

}
